/**
 * 缓存变量到存储：localStorage或sessionStorage.
 */
class cacheMemory {
    /**
     *
     * @param prefix 前缀
     * @param strategy 存储类型：L 对应localStorage，S对应sessionStorage
     */
    constructor(prefix, strategy = 'L') {
        this.prefix = prefix;
        this.Storage = strategy === 'S' ? window.sessionStorage : window.localStorage;
    }
    /**
     * @param {String} key
     * @param {*} value
     */
    set(...args) {
        this.Storage.setItem(...this._transformArgs(args));
    }
    /**
     * @param {*} key
     * @param {*} decode
     */
    get(...args) {
        const [_, key] = args;
        const cache = this.Storage.getItem(...this._transformArgs(args));
        if (cache && key) {
            return JSON.parse(cache);
        }
        return cache;
    }
    /**
     * @param {*} key
     */
    remove(...args) {
        this.Storage.removeItem(...this._transformArgs(args));
    }
    batchSet(datas) {
        for (const [key, value] of Object.entries(datas)) {
            this.set(key, value);
        }
    }
    clear(cb) {
        var _a;
        let len = this.Storage.length;
        const keys = [];
        for (let i = 0; i < len; i++) {
            let _key = this.Storage.key(i);
            keys.push(_key);
        }
        for (let i = 0; i < keys.length; i++) {
            if (((_a = keys[i]) === null || _a === void 0 ? void 0 : _a.indexOf(`${this.prefix}`)) === 0) {
                this.Storage.removeItem(keys[i]);
            }
        }
        cb && cb();
    }
    _getKey(key) {
        return `${this.prefix}:${key}`;
    }
    /**
     * @todo 验证参数
     * @param {Array} args
     */
    _transformArgs(args) {
        const [key] = args;
        args[0] = this._getKey(key);
        return args;
    }
}

export { cacheMemory as default };
